import axios from "axios";
import { useToken } from "@/store/auth";
import { TokenI } from "@/models/user";

export const API_URL = "/";

const $api = axios.create({
  withCredentials: true,
  baseURL: API_URL,
});

$api.interceptors.request.use((config) => {
  const accessToken = useToken.getState().credentials?.access;

  if (accessToken) config.headers.Authorization = `Bearer ${accessToken}`;

  return config;
});

$api.interceptors.response.use(
  (config) => {
    return config;
  },
  async (error) => {
    const originalRequest = error.config;

    if (
      error.response.status === 401 &&
      error.config &&
      !error.config.isRetry
    ) {
      originalRequest.isRetry = true;
      const refreshToken = useToken.getState().credentials?.refresh;

      if (!refreshToken) {
        useToken.getState().logout();
        return;
      }

      try {
        const response = await $api.post<TokenI>(`api/token/refresh/`, {
          refresh: refreshToken,
        });
        useToken.getState().setCredentials({
          access: response.data.access,
          refresh: refreshToken,
        });
        return $api.request(originalRequest);
      } catch (e) {
        console.log("Unauthorized");
        useToken.getState().logout();
      }
    }
    throw error;
  }
);

export default $api;
